<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Excel extends CI_Controller {
    
    private $data = array();

    public function  __construct() {
        parent::__construct();

   		//check session
        if( !$this->session->userdata('isLoggedIn') ) {
            redirect(base_url().'trang-quan-ly-truyen.html', 'refresh');
        }
        //Load Helper and library
        $this->load->helper("url");
        $this->load->library("ci_smarty");
        $this->load->helper("text"); 
        $this->data['base_url'] = base_url();
        $this->data['root_url'] = $this->config->item('root_url');
        $this->load->library('pagination'); 
        
        $this->data['nameAdmin'] = $this->session->userdata('name');

        //Load Model
        $this->load->Model("admin/Mexcel");
        $this->load->Model("admin/Mchapter");
        $this->load->Model("admin/Mbook");
    }

    public function importExcel()
    {
    	if($this->input->post()){
    		// load upload file excel
            $excel = $this->Mexcel->uploadExcel();
            
            if($excel['file_name'] !='')
            {
		    	// load library excel
		    	$this->load->library("excel");
		    	
		    	// get file excel
		    	$file = APPPATH. '../public/frontend/excel/'.$excel['file_name'] ;
		    	
		    	//here i used microsoft excel 2007
		    	$objReader = PHPExcel_IOFactory::createReader('Excel5');
		    	
		    	//set to read only
		    	$objReader->setReadDataOnly(true);
		    	
		    	//load excel file 	
		    	$objPHPExcel = $objReader->load($file);
		    	$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
		    	$i = 0;
		    	$n = count($sheetData);
		    	$prevId = NULL;
				foreach ($sheetData as $data) {
					if ($i == 0) {
						$i++;
						continue; //Cột đầu tiên ko dùng
					}
					$book_id = $this->input->post('bookID');
					
					$param['book_id'] = $book_id;
					$param['no'] = $data['C'];
					$param['volume_no'] = $data['D'];
					$param['name'] = trim($data['E']);
					$param['uname'] = mb_strtolower(url_title(removesign($param['name'])));
					$param['open'] = $data['G'];

					$book = $this->Mbook->getBookNameByBookID($book_id);
					
					$param['page_title'] = $book['name'].' - '.trim($data['E']).'- Truyện Online';
					$param['page_keyword'] = trim($data['I']);
					$description = character_limiter(strip_tags(trim($data['K'])), 120);
					$description = trim($description, '-');
					$param['page_description'] = 'Truyện '.$book['name'].' Online - '.$description;
					$param['description'] = trim($data['K']);
					$param['mob_description'] = trim($data['L']);
					$param['status'] = $data['M'];
					$param['prev_no'] = $prevId;
					if ($prevId == NULL) {
						$param['next_no'] = NULL;
					} else {
						$param['next_no'] = $prevId + 2;
					}
					
					$lastID = $this->Mchapter->insertChapter($param);
					$prevId = $lastID;
					
				}
				unlink($file);
				redirect(base_url()."admin/list-chapter.html"); 
            }else {
            	echo 'Bạn Quên Chọn File Excel Rồi. Nhớ Chọn File nhé!';
            }
    	}
    }
    
	public function exportExcel()
    {
    	echo 'chưa làm nhé';
    	exit;
    	// load library excel
    	$this->load->library('excel');
		$sheet = new PHPExcel();
		$sheet->getProperties()->setTitle('Attendance Report')->setDescription('Attendance Report');
		$sheet->setActiveSheetIndex(0);
		
		// Field names in the first row
		// load chapter list
    	$fields = $this->Mchapter->getChapterAll();
        if(!$fields)
            return false;
            
    	$col = 0;
		foreach ($fields as $field) {
			$sheet->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
			$col++;
		}
	    $row = 2;
		foreach ($query->result() as $data) {
			$col = 0;
			foreach ($fields as $field) {
				$sheet->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
				$col++;
			}
			$row++;
		}
		$sheet->setActiveSheetIndex(0);
		$sheet_writer = PHPExcel_IOFactory::createWriter($sheet, 'Excel5');
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="att_report_'.date('dMy').'.xls"');
		header('Cache-Control: max-age=0');
		
		$sheet_writer->save('php://output');
    }
}